package org.example.translate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.http.util.LangUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

public class TranslateTask implements Runnable {
	private static final String TAG = "TranslateTask";
	private static final String GOOGLE_TRANSLATE_LINK = "http://ajax.googleapis.com/ajax/services/language/translate";
	private static final String REFERER_LINK = "http://www.pragprog.com/titles/eband3/hello-android";
	private final TranslateActivity translate;
	private final String original, from, to;
	
	TranslateTask(TranslateActivity translate, String original, String from, String to)
	{
		this.translate = translate;
		this.original = original;
		this.from = from;
		this.to = to;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		// translate the original text to target language
		String trans = doTranslate(original, from, to);
		translate.setTranslated(trans);
		
		// then translate what we got back to the first language.
		String retrans = doTranslate(trans, from, to);
		translate.setRetranslated(retrans);
	}

	private String doTranslate(String original, String from, String to) {
		// TODO Auto-generated method stub
		String result = translate.getResources().getString(R.string.translation_error);
		HttpURLConnection con = null;
		
		try {
			if(Thread.interrupted())
			{
				throw new InterruptedException();
			}
			
			// build the RestFUL query for Google API
			String q = URLEncoder.encode(original, "UTF8");
			
			URL url = new URL(GOOGLE_TRANSLATE_LINK + "&v=1.0" + "&q=" + q + "&langpair=" + from + "%7C" + to);
			con = (HttpURLConnection)url.openConnection();
			con.setReadTimeout(10000); // 10s
			con.setConnectTimeout(15000); // 15s
			con.setRequestMethod("GET");
			con.addRequestProperty("Referer", REFERER_LINK);
			con.setDoInput(true);
			
			con.connect();
			
			// check if task has been interrupted
			if(Thread.interrupted())
			{
				throw new InterruptedException();
			}
			
			// read the result from query
			BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF8"));
			String payLoad = reader.readLine();
			reader.close();
			
			// parse to get the translated text
			JSONObject jsonObject = new JSONObject(payLoad);
			result = jsonObject.getJSONObject("responseData")
							   .getString("translatedText")
							   .replace("&#39", "'")
							   .replace("&amp;", "&")
							   ;
			// check if task is interrupted
			if(Thread.interrupted())
			{
				throw new InterruptedException();
			}
		} catch (IOException e) {
			// TODO: handle exception
		} catch (JSONException e) {
			// TODO: handle exception
		} catch (InterruptedException e) {
			// TODO: handle exception
		}finally
		{
			// release connection
			if(con != null)
			{
				con.disconnect();
			}
		}
		
		// ALL are done
		Log.d(TAG, "=> returned:" + result);
		return result;
	}
}
